package cn.com.okgo.request.base;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.util.List;
import java.util.Map;

import cn.com.okgo.model.HttpParams;
import cn.com.okgo.model.Bytes;
import cn.com.okgo.utils.HttpUtils;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by luwenlong on 2017/8/28.
 */

public abstract class BodyRequest<T, R extends BodyRequest> extends BaseRequest<T, R> implements IBody<R> {

    protected transient MediaType mediaType;        //上传的MIME类型
    protected String content;                       //上传的文本内容
    protected transient File file;                  //单纯的上传一个文件

    protected BodyRequest(String url) {
        super( url );
    }

    @Override
    protected RequestBody generateRequestBody() {
        if (content != null && mediaType != null)
            return RequestBody.create( mediaType, content );    //上传字符串数据
        if (file != null && mediaType != null)
            return RequestBody.create( mediaType, file );          //上传一个文件
        return HttpUtils.generateMultipartRequestBody( params );
    }


    @Override
    public R upString(String string) {
        this.content = string;
        this.mediaType = HttpParams.MEDIA_TYPE_PLAIN;
        return (R) this;
    }

    @Override
    public R upString(String string, MediaType mediaType) {
        this.content = string;
        this.mediaType = mediaType;
        return (R) this;
    }

    @Override
    public R upJson(String json) {
        this.content = json;
        this.mediaType = HttpParams.MEDIA_TYPE_JSON;
        return (R) this;
    }

    @Override
    public R upJson(JSONObject jsonObject) {
        this.content = jsonObject.toString();
        this.mediaType = HttpParams.MEDIA_TYPE_JSON;
        return (R) this;
    }

    @Override
    public R upJson(JSONArray jsonArray) {
        this.content = jsonArray.toString();
        this.mediaType = HttpParams.MEDIA_TYPE_JSON;
        return (R) this;
    }

    @Override
    public R upFile(File file) {
        this.file = file;
        this.mediaType = HttpUtils.guessMimeType( file.getName() );
        return (R) this;
    }

    @Override
    public R upFile(File file, MediaType mediaType) {
        this.file = file;
        this.mediaType = mediaType;
        return (R) this;
    }

    @Override
    public R upFile(String key, File file) {
        params.put( key, file );
        return (R) this;
    }

    @Override
    public R upFile(String key, List<File> files) {
        params.putFileParams( key, files );
        return (R) this;
    }

    @Override
    public R upFile(Map<String, File> map) {
        params.putFileParams( map );
        return (R) this;
    }

    @Override
    public R upByts(Bytes bytes) {
        params.putBytesParams(bytes);
        return (R) this;
    }

    @Override
    public R upBytes(List<Bytes> list) {
        params.putBytesParams(list);
        return (R) this;
    }
}